#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "crypto/types.h"
#include "crypto/log.h"
#include "crypto/errors.h"

// default outputfile = stdout
int logFileFd = 0;

int LogSetFile(char *path)
{
    int fd = open(path, O_WRONLY | O_APPEND | O_CREAT);
    if (fd == -1)
    {
        export(CODE_FILE_OPERATE_FAILED, "File open failed!");
    }
    logFileFd = fd;
}

void loger(enum LogLevel level, char *file, char *baseFile, int line, char *data)
{
    switch (level)
    {
    case LOG_LEVEL_INFO:
        write(logFileFd, "[INFO] ", 7);
        break;
    case LOG_LEVEL_DEBUG:
        write(logFileFd, "[DEBUG] ", 8);
        break;
    case LOG_LEVEL_WARNING:
        write(logFileFd, "[WARNING] ", 10);
        break;
    case LOG_LEVEL_ERROR:
        write(logFileFd, "[ERROR] ", 8);
        break;
    default:
        write(logFileFd, "[UNKNOW] ", 9);
    }
    char buffer[2048];
    time_t tTime;
    time(&tTime);
    struct tm *tmTime = localtime(&tTime);
    // sprintf(buffer, "[%d-%d-%d %d:%d:%d] FILE: %s BASEFILE: %s LINE: %d MSG: %s\n",
    //         tmTime->tm_year,
    //         tmTime->tm_mon + 1,
    //         tmTime->tm_mday,
    //         tmTime->tm_hour,
    //         tmTime->tm_min,
    //         tmTime->tm_sec,
    //         file, baseFile, line, data);
    sprintf(buffer, "[%d-%d-%d %d:%d:%d] MSG: %s\n",
            tmTime->tm_year,
            tmTime->tm_mon + 1,
            tmTime->tm_mday,
            tmTime->tm_hour,
            tmTime->tm_min,
            tmTime->tm_sec,
            data);
    write(logFileFd, buffer, strlen(buffer));
}